﻿using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using HardMock.Domain;

namespace HardMock.Recording
{
    class InMemoryRepository : IRepository
    {
        private readonly IDictionary<string, CallResult> repository;

        private readonly ISerializer serializer;

        public InMemoryRepository(ISerializer serializer)
        {
            this.serializer = serializer;
            repository = new ConcurrentDictionary<string, CallResult>();
        }

        public InMemoryRepository(ISerializer serializer, Stream recordedCallsBin)
            : this(serializer)
        {
            repository = (IDictionary<string, CallResult>)serializer.Deserialize(recordedCallsBin);
        }

        public CallResult TryGet(string identifier, out bool succeed)
        {
            succeed = false;
            if (!repository.ContainsKey(identifier))
            {
                return null;
            }

            succeed = true;
            return repository[identifier];
        }

        public void Update(string identifier, CallResult callResult)
        {
            repository[identifier] = callResult;
        }

        public void Serialize(Stream stream)
        {
            try
            {
                serializer.Serialize(repository, stream);
            }
            catch (SerializationException e)
            {
                throw new HardMockException(e.Message);
            }
        }
    }
}